package com.jsyl.lwbk.business.handle;

import com.jsyl.lwbk.business.domain.Center;
import com.jsyl.lwbk.business.domain.Child;
import com.jsyl.lwbk.business.domain.EvaluateReport;
import com.jsyl.lwbk.business.domain.EvaluateScore;
import com.jsyl.lwbk.business.mapper.*;
import com.jsyl.lwbk.business.vo.ReportEvaluateVO;
import com.jsyl.lwbk.business.vo.ReportProjectVO;
import com.jsyl.lwbk.common.exception.BusinessException;
import com.jsyl.lwbk.common.utils.DateUtils;
import com.jsyl.lwbk.common.utils.StringUtils;
import com.jsyl.lwbk.common.utils.pdf.HtmlToPdf1Utils;
import com.jsyl.lwbk.system.mapper.SysDictDataMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.URL;
import java.util.*;

/**
 * @author xiaoshu
 * @date 2020-12-26 14:32
 * @desc 生成测评PDF文件
 **/
@Component
public class CreateEvaluateReportPDFHandle {
    private static final Logger log = LoggerFactory.getLogger(CreateEvaluateReportPDFHandle.class);

    /**
     * 原先定义地址
     */
    public static String filePath = "evaluation";

    @Autowired
    EvaluateReportMapper evaluateReportMapper;
    @Autowired
    EvaluateScoreMapper evaluateScoreMapper;
    @Autowired
    ChildMapper childMapper;
    @Autowired
    SysDictDataMapper sysDictDataMapper;
    @Autowired
    EvaluateRecordMapper evaluateRecordMapper;
    @Autowired
    AliOssHandle aliOssHandle;
    @Autowired
    CenterMapper centerMapper;
    @Autowired
    CalculateEvaluateScoreHandle calculateEvaluateScoreHandle;

    /**
     * 生成PDF文件链接
     *
     * @param evaluateNumber
     * @return
     */
    public String getEvaluateReportUrl(String evaluateNumber) {
        EvaluateReport evaluateReport = evaluateReportMapper.findByEvaluateNumber(evaluateNumber);
        if (evaluateReport == null) {
            throw new BusinessException("请选择测评");
        } else if (evaluateReport.getStatus() != 0) {//测评未完成，不给导出测评
            throw new BusinessException("测评未完成，无法导出对应测评PDF");
        }
        if (StringUtils.isNotEmpty(evaluateReport.getEvaluateUrl())) {
            return evaluateReport.getEvaluateUrl();
        }

        //判断是否存在分数计算（方便后续补偿）
        if (evaluateScoreMapper.selectCountScoreByEvaluateNum(evaluateNumber) < 1) {
            calculateEvaluateScoreHandle.handle(evaluateNumber, evaluateReport.getUpdateBy());
        }

        //未生成记录时，去生成报告
        String dest = createRender1(evaluateReport);
        File file = new File(dest);
        //保存报告到oss
        String fileUrl = null;
        try {
            String fileName = file.getName();
            fileUrl = aliOssHandle.upload(fileName, null, new FileInputStream(file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // evaluateReport = new EvaluateReport();
        evaluateReport.setEvaluateUrl(fileUrl);
        evaluateReportMapper.updateById(evaluateReport);

        return fileUrl;
    }

    /**
     * 创建渲染pdf
     *
     * @return
     */
    public String createRender(EvaluateReport evaluateReport) {
        // 创建渲染PDF内容
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> evaluateMap = new HashMap<>();

        Child child = childMapper.selectById(evaluateReport.getChildId());
        Center center = centerMapper.selectById(child.getCenterId());

        String evaluateTime = DateUtils.dateTime(evaluateReport.getUpdateTime());
        Map<String, Object> ageMap = DateUtils.toAge(Integer.parseInt(child.getBirthYear()), Integer.parseInt(child.getBirthMonth()));

        String memberTimeCode = "";
        String number = "";

        List<Child> childList = childMapper.getChildListByCenterId(child.getCenterId());
        Integer n = null;
        if (childList.size() != 0) {
            Integer i = 1;
            for (Child childView : childList) {
                if (childView.getId().equals(child.getId())) {
                    n = i;
                }
                i++;
            }
        }
        if (evaluateTime != null) {
            memberTimeCode = getCode(evaluateTime);
            if (n >= 100) {
                number = String.valueOf(n);
            } else if (n >= 10) {
                number = "0" + String.valueOf(n);
            } else {
                number = "00" + String.valueOf(n);
            }
            map.put("sn", center.getSn() + "-" + memberTimeCode + number);
        }
        map.put("name", child.getName());
        map.put("date", DateUtils.dateTime(evaluateReport.getUpdateTime()));
        map.put("sex", sysDictDataMapper.selectDictLabel("sys_user_sex", String.valueOf(child.getSex())));
        map.put("grade", String.valueOf(child.getGrade()));
        map.put("age", ageMap.get("age"));
        map.put("birthday", child.getBirthYear() + "-" + child.getBirthMonth() + "-" + child.getBirthDay());
        map.put("teacher", evaluateReport.getUpdateBy());

        // 分数相关处理
        List<ReportProjectVO> rpvList = new ArrayList<>();
        List<Integer> projectList = evaluateScoreMapper.selectProjectByEvaluateNum(evaluateReport.getEvaluateNumber());
        // 循环处理从每个大类到小类
        for (Integer project : projectList) {
            // 大类处理
            ReportProjectVO rpv = new ReportProjectVO();
            List<ReportEvaluateVO> revList = new ArrayList<>();
            rpv.setSubjectName(sysDictDataMapper.selectDictLabel("business_project_module", String.valueOf(project)));
            List<EvaluateScore> evaluateScores = evaluateScoreMapper.selectByProjectAndEvaluateNum(project, evaluateReport.getEvaluateNumber());
            for (EvaluateScore evaluateScore : evaluateScores) {
                if (evaluateScore.getEvaluateModule() != null) {
                    ReportEvaluateVO rev = new ReportEvaluateVO();
                    rev.setTypeName(sysDictDataMapper.selectDictLabel("business_evaluate_module", String.valueOf(evaluateScore.getEvaluateModule())));
                    rev.setConclusion(evaluateScore.getReportRemark());
                    rev.setScore(String.valueOf(evaluateScore.getScore()));
                    evaluateMap.put(evaluateScore.getEvaluateModule() + "Score", rev.getScore());
                    evaluateMap.put(evaluateScore.getEvaluateModule() + "Conclusion", rev.getConclusion());
                    evaluateMap.put(evaluateScore.getEvaluateModule() + "Name", rev.getTypeName());
                    if (evaluateScore.getProjectModule() == 3) {
                        evaluateMap.put("cognitionScore", rev.getScore());
                        evaluateMap.put("cognitionConclusion", rev.getConclusion());
                        evaluateMap.put("cognitionName", rev.getTypeName());
                    } else if (evaluateScore.getProjectModule() == 4) {
                        evaluateMap.put("languageScore", rev.getScore());
                        evaluateMap.put("languageConclusion", rev.getConclusion());
                        evaluateMap.put("languageName", rev.getTypeName());
                    } else {
                        evaluateMap.put("contactScore", rev.getScore());
                        evaluateMap.put("contactConclusion", rev.getConclusion());
                        evaluateMap.put("contactName", rev.getTypeName());
                    }
                    revList.add(rev);
                } else {
                    // 设置大类 并将大类对应的小类归纳进大类
                    rpv.setResultScore(String.valueOf(evaluateScore.getScore()));
                    rpv.setAbility(evaluateScore.getReportRemark());
                    // 大类总分 = 大类下的题目数 * 4
                    // Integer questionNum = evaluateRecordMapper.selectQuestionNumByProject(project, evaluateNumber);
                    rpv.setInitScore(evaluateScore.getTotalScore());
                    evaluateMap.put(String.valueOf(project), evaluateScore.getScore() + "/" + evaluateScore.getTotalScore());
                    rpvList.add(rpv);
                }
            }
            rpv.setRdvList(revList);
        }
        map.put("rpvList", rpvList);
        map.put("detailMap", evaluateMap);

        String dest = null;
        try {
            String fileName = map.get("name") + "-" + evaluateReport.getEvaluateNumber() + "-" + new Random().nextInt(9999);
            URL url = this.getClass().getClassLoader().getResource("");
            dest = HtmlToPdf1Utils.toPdf(map, url, fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dest;
    }

    //学期编码
    public String getCode(String memberTime) {

        if (memberTime.compareTo(memberTime.substring(0, 5) + "02-15") <= 0) {
            memberTime = memberTime.substring(0, 4).substring(2, 4) + "04";
        } else if (memberTime.compareTo(memberTime.substring(0, 5) + "07-31") <= 0) {
            memberTime = memberTime.substring(0, 4).substring(2, 4) + "01";
        } else if (memberTime.compareTo(memberTime.substring(0, 5) + "09-30") <= 0) {
            memberTime = memberTime.substring(0, 4).substring(2, 4) + "03";
        } else {
            memberTime = memberTime.substring(0, 4).substring(2, 4) + "02";
        }

        return memberTime;
    }

    public String createRender1(EvaluateReport evaluateReport) {
        // 创建渲染PDF内容
        Map<String, Object> map = new HashMap<>();

        Child child = childMapper.selectById(evaluateReport.getChildId());
        Center center = centerMapper.selectById(child.getCenterId());

        String evaluateTime = DateUtils.dateTime(evaluateReport.getUpdateTime());
        Map<String, Object> ageMap = DateUtils.toAge(Integer.parseInt(child.getBirthYear()), Integer.parseInt(child.getBirthMonth()));

        String memberTimeCode = "";
        String number = "";

        List<Child> childList = childMapper.getChildListByCenterId(child.getCenterId());
        Integer n = null;
        if (childList.size() != 0) {
            Integer i = 1;
            for (Child childView : childList) {
                if (childView.getId().equals(child.getId())) {
                    n = i;
                }
                i++;
            }
        }
        if (evaluateTime != null) {
            memberTimeCode = getCode(evaluateTime);
            if (n!=null && n >= 100) {
                number = String.valueOf(n);
            } else if (n!=null &&n >= 10) {
                number = "0" + String.valueOf(n);
            } else {
                number = "00" + String.valueOf(n);
            }
            map.put("sn",  memberTimeCode + number);
        }
        // 基础信息
        map.put("name", child.getName());
        map.put("date", DateUtils.dateTime(evaluateReport.getUpdateTime()));
        map.put("sex", sysDictDataMapper.selectDictLabel("sys_user_sex", String.valueOf(child.getSex())));
        map.put("grade", String.valueOf(child.getGrade()));
        map.put("age", ageMap.get("age"));
        map.put("birthday", child.getBirthYear() + "-" + child.getBirthMonth() + "-" + child.getBirthDay());
        map.put("teacher", evaluateReport.getUpdateBy());

        // 表格中的数据
        Map<String, Object> projectMap = new HashMap<>();
        Map<String, Object> moduleMap = new HashMap<>();
        // 详细数据
        Map<String, Object> detailMap = new HashMap<>();

        // 情绪处理总分
        Integer emotionProcessScore = 0;
        // 情绪状态总分
        Integer emotionalStateScore = 0;
        // 自我指向总分
        Integer selfDirectedScore = 0;
        // 环境与他人总分
        Integer environmentScore = 0;

        // 按照测评编号查询档案表中的全部分数以及反馈信息
        List<EvaluateScore> evaluateScoreList = evaluateScoreMapper.findByEvaluateNumber(evaluateReport.getEvaluateNumber());
        for (EvaluateScore evaluateScore : evaluateScoreList) {
            if (evaluateScore.getEvaluateModule() == null) { // 测评类型为空代表大类
                projectMap.put(evaluateScore.getProjectModule() + "tableName", sysDictDataMapper.selectDictLabel("business_project_module", String.valueOf(evaluateScore.getProjectModule())));
                projectMap.put(evaluateScore.getProjectModule() + "tableScore", evaluateScore.getScore() + "/" + evaluateScore.getTotalScore());
                projectMap.put(evaluateScore.getProjectModule() + "tableRemark", evaluateScore.getReportRemark());
                // 构音小类合并为一个
                if (evaluateScore.getProjectModule().equals(5)) {
                    moduleMap.put("7tableName", sysDictDataMapper.selectDictLabel("business_evaluate_module", String.valueOf(7)));
                    moduleMap.put("7tableScore", evaluateScore.getScore());
                }

                detailMap.put(evaluateScore.getProjectModule() + "", evaluateScore.getScore());
            } else { // 小类型
                if (evaluateScore.getEvaluateModule().equals(10)) {
                    // 情绪状态归为情绪状态
                    emotionProcessScore = evaluateScore.getScore();
                } else if (evaluateScore.getEvaluateModule().equals(19) || evaluateScore.getEvaluateModule().equals(20) || evaluateScore.getEvaluateModule().equals(21) || evaluateScore.getEvaluateModule().equals(22)) {
                    // 情绪感知（4分）情绪理解（12分）情绪表达（16分）情绪管理（4分）归为情绪处理
                    emotionalStateScore += evaluateScore.getScore();
                } else if (evaluateScore.getEvaluateModule().equals(23) || evaluateScore.getEvaluateModule().equals(24) || evaluateScore.getEvaluateModule().equals(25)) {
                    selfDirectedScore += evaluateScore.getScore();
                } else if (evaluateScore.getEvaluateModule().equals(26) || evaluateScore.getEvaluateModule().equals(27) || evaluateScore.getEvaluateModule().equals(28)) {
                    environmentScore += evaluateScore.getScore();
                } else {
                    moduleMap.put(evaluateScore.getEvaluateModule() + "tableName", sysDictDataMapper.selectDictLabel("business_evaluate_module", String.valueOf(evaluateScore.getEvaluateModule())));
                    moduleMap.put(evaluateScore.getEvaluateModule() + "tableScore", evaluateScore.getScore());
                }
                detailMap.put(evaluateScore.getEvaluateModule() + "Name", sysDictDataMapper.selectDictLabel("business_evaluate_module", String.valueOf(evaluateScore.getEvaluateModule())));
                detailMap.put(evaluateScore.getEvaluateModule() + "Score", evaluateScore.getScore());
                detailMap.put(evaluateScore.getEvaluateModule() + "Conclusion", evaluateScore.getReportRemark());
            }
        }
        moduleMap.put("10tableName", sysDictDataMapper.selectDictLabel("business_evaluate_module", String.valueOf(10)));
        moduleMap.put("10tableScore", emotionProcessScore);
        moduleMap.put("11tableName", sysDictDataMapper.selectDictLabel("business_evaluate_module", String.valueOf(11)));
        moduleMap.put("11tableScore", emotionalStateScore);
        moduleMap.put("12tableName", sysDictDataMapper.selectDictLabel("business_evaluate_module", String.valueOf(12)));
        moduleMap.put("12tableScore", selfDirectedScore);
        moduleMap.put("13tableName", sysDictDataMapper.selectDictLabel("business_evaluate_module", String.valueOf(13)));
        moduleMap.put("13tableScore", environmentScore);
        map.put("projectMap", projectMap);
        map.put("moduleMap", moduleMap);
        map.put("detailMap", detailMap);

        String dest = null;
        try {
            String fileName = map.get("name") + "-" + evaluateReport.getEvaluateNumber() + "-" + new Random().nextInt(9999);
            URL url = this.getClass().getClassLoader().getResource("");
            dest = HtmlToPdf1Utils.toPdf(map, url, fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dest;
    }

}
